#!/bin/bash
###############################
#测试脚本
###############################

set -x


function check() {
	# assume that ruby rpm already built.
	cd /root/rpmbuild/BUILD/ruby-2.6.9
	# test basic known bugs, require 100% pass
	make test &> ruby-test.log
	local is_success=$(cat ruby-test.log | grep "test succeeded" | wc -l)
	if [[ $is_success -ne 1 ]]; then
		echo "RETURN FAILED"
		return
	fi

	# test all, allow 10% failure
	make test-all RUBYOPT="-w" &> ruby-test-all.log
	local total=$(cat ruby-test-all.log | tail -10 | grep -E "tests.*assertions.*failures.*errors.*skips" | awk '{print $1}')
	local failures=$(cat ruby-test-all.log | tail -10 | grep -E "tests.*assertions.*failures.*errors.*skips" | awk '{print $5}')
	local errors=$(cat ruby-test-all.log | tail -10 | grep -E "tests.*assertions.*failures.*errors.*skips" | awk '{print $7}')
	local is_all_in_failure_percent=$(python3 -c "res=$failures.0/$total+$errors.0/$total; print(res <= 0.1);")
	if [[ $is_all_in_failure_percent != "True" ]]; then
		echo "RETURN FAILED"
		return
	fi

	# test spec, allow 10% failure
	make test-spec &> ruby-test-spec.log
	local total=$(cat ruby-test-spec.log | grep -E "files.*examples.*failures" | awk '{print $5}')
	local failures=$(cat ruby-test-spec.log | grep -E "files.*examples.*failures" | awk '{print $7}')
	local errors=$(cat ruby-test-spec.log | grep -E "files.*examples.*failures" | awk '{print $9}')
	local is_spec_in_failure_percent=$(python3 -c "res=$failures.0/$total+$errors.0/$total; print(res <= 0.1);")
	if [[ $is_spec_in_failure_percent != "True" ]]; then
                echo "RETURN FAILED"
		return
        fi

	echo "RETURN SUCCESS"
}


# DO NOT CHANGE THE MAIN FUNCTION
function main()
{
	ret=$(check)
	if [[ $ret == *'RETURN SUCCESS' ]]; then
		echo "test scripts success"
	else
		echo "test scripts failed"
	fi
}

main
